package com.tarena.lbs.coupon.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import com.tarena.lbs.coupon.pojo.param.CouponEnableStatusParam;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.query.CouponQuery;
import com.tarena.lbs.coupon.pojo.query.UserCouponCodeQuery;
import com.tarena.lbs.coupon.pojo.query.UserCouponQuery;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.pojo.vo.UserCouponsVO;
import com.tarena.lbs.coupon.service.CouponService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * 处理和优惠券数据业务有关的接口
 */
@RestController
@Slf4j
@Tag(name="优惠券模块")
@RequestMapping("/admin/marketing/coupon/info")
public class CouponController {
    
    @Autowired
    private CouponService couponService;

    @Operation(summary = "查询当前商家优惠券分页列表")
    @PostMapping("/list")
    public Result<PageResult<CouponVO>> pageList(@RequestBody CouponQuery query) throws BusinessException {
        log.info("查询优惠券列表，参数: {}", query);
        
        // 确保优惠券名称被正确处理为字符串，防止数字被错误解析
        if (query.getCouponName() != null) {
            // 直接使用String.valueOf确保即使输入是数字也被当作字符串处理
            query.setCouponName(String.valueOf(query.getCouponName()));
            log.debug("处理后的优惠券名称: {}", query.getCouponName());
        }
    
        // 确保优惠券类型参数的有效性
        if (query.getCouponType() != null) {
            try {
                query.setCouponType(Integer.parseInt(String.valueOf(query.getCouponType())));
                log.debug("处理后的优惠券类型: {}", query.getCouponType());
            } catch (NumberFormatException e) {
                log.error("优惠券类型格式错误", e);
                throw new BusinessException("-1", "优惠券类型格式错误");
            }
        }
    
        // 确保优惠券状态参数的有效性
        if (query.getStatus() != null) {
            try {
                query.setStatus(Integer.parseInt(String.valueOf(query.getStatus())));
                log.debug("处理后的优惠券状态: {}", query.getStatus());
            } catch (NumberFormatException e) {
                log.error("优惠券状态格式错误", e);
                throw new BusinessException("-1", "优惠券状态格式错误");
            }
        }
        
        // 执行查询
        PageResult<CouponVO> result = couponService.pageList(query);
        return new Result<>(result);
    }

    @Operation(summary = "新增优惠券")
    @PostMapping("/save")
    public Result<Void> addCoupon(@Valid @RequestBody CouponParam couponParam) throws BusinessException{
        log.info("新增优惠券，参数: {}", couponParam);
        couponService.createCoupon(couponParam);
        return Result.success();
    }

    @Operation(summary = "查询优惠券详情")
    @GetMapping("/detail/{id}")
    public Result<CouponVO> detailById(@PathVariable("id") Integer Id) throws BusinessException{
        log.info("查询优惠券详情，ID: {}", Id);
        CouponVO couponVO = couponService.getCouponDetail(Id);
        return new Result<>(couponVO);
    }
    

    @Operation(summary = "删除优惠券")
    @PostMapping("/delete/{id}")
    public Result<Void> deleteCoupon(@PathVariable("id") Integer id) throws BusinessException{
        log.info("删除优惠券，ID: {}", id);
        couponService.deleteCouponId(id);
        return Result.success();
    }

    @Operation(summary = "领取优惠券")
    @PostMapping("/marketing/user/receive/save")
    public Result<Void> receiveCoupon(@RequestBody UserCouponsParam param) throws BusinessException {
        return null; // 保持原有实现
    }

    @Operation(summary = "用户领取优惠券列表")
    @PostMapping("/marketing/user/receive/list")
    public Result<PageResult<UserCouponsVO>> receiveList(@RequestBody UserCouponQuery couponQuery)throws BusinessException{
        return null;
    }

    @Operation(summary = "查看优惠券码的二维码图片")
    @PostMapping("/marketing/user/receive/detail")
    public Result<UserCouponsVO> receiveDetail(@RequestBody UserCouponCodeQuery query)
        throws BusinessException{
        return null;
    }

    @Operation(summary = "更新优惠券启用状态")
    @PostMapping({"/adminCouponStatus"})
    public Result<Void> adminCouponStatus(@Valid @RequestBody CouponEnableStatusParam param) throws BusinessException {
        log.info("更新优惠券启用状态，参数: {}", param);
        couponService.updateCouponEnableStatus(param.getId(), param.getEnableStatus());
        return Result.success();
    }
    /**
     * 处理请求体参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationException(MethodArgumentNotValidException ex) {
        log.error("参数验证异常: {}", ex.getMessage(), ex);
        // 获取第一个验证错误的信息
        String errorMsg = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.fail("-1", errorMsg);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException ex) {
        log.error("业务异常: {}", ex.getMessage(), ex);
        return Result.fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception ex) {
        log.error("系统异常: {}", ex.getMessage(), ex);
        return Result.fail("-1", "系统内部错误，请稍后重试");
    }
}